{% extends 'layout.html' %}

{% block content %}
<div class="container py-5">
    <div class="row">
        <!-- 购物车商品列表 -->
        <div class="col-md-8">
            <div class="card">
                <div class="card-header bg-white">
                    <h3 class="mb-0">购物车</h3>
                </div>
                <div class="card-body">
                    <div id="cart-items-container">
                        <!-- 购物车商品将在这里动态加载 -->
                        {% if cart_items %}
                            {% for item in cart_items %}
                            <div class="row mb-3 align-items-center cart-item" data-product-id="{{ item.product.product_code }}">
                                <div class="col-md-2">
                                    {% if item.product.image_url %}
                                    <img src="{{ item.product.image_url }}" alt="{{ item.product.name }}" class="img-fluid">
                                    {% else %}
                                    <div class="img-placeholder bg-light" style="width:100%; height:100px; display:flex; align-items:center; justify-content:center;">
                                        <i class="fas fa-box-open fa-2x text-muted"></i>
                                    </div>
                                    {% endif %}
                                </div>
                                <div class="col-md-4">
                                    <h5>{{ item.product.name }}</h5>
                                    <small class="text-muted">{{ item.product.specification|default:"标准规格" }}</small>
                                </div>
                                <div class="col-md-2 text-right">
                                    ¥{{ item.product.price }}
                                </div>
                                <div class="col-md-2">
                                    <div class="input-group">
                                        <button class="btn btn-outline-secondary btn-sm quantity-decrease" type="button">-</button>
                                        <input type="text" class="form-control form-control-sm text-center quantity" value="{{ item.quantity }}" readonly>
                                        <button class="btn btn-outline-secondary btn-sm quantity-increase" type="button">+</button>
                                    </div>
                                </div>
                                <div class="col-md-2 text-right">
                                    <span class="item-subtotal">¥{% widthratio item.product.price 1 item.quantity %}</span>
                                    <button class="btn btn-link text-danger btn-sm remove-item" style="font-size:12px;">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                            {% endfor %}
                        {% else %}
                            <div class="text-center py-5">
                                <i class="fas fa-shopping-cart fa-3x text-muted mb-3"></i>
                                <p class="text-muted">您的购物车是空的</p>
                                <a href="{% url 'product_list' %}" class="btn btn-primary">继续购物</a>
                            </div>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>

        <!-- 订单汇总 -->
        <div class="col-md-4">
            <div class="card">
                <div class="card-header bg-white">
                    <h3 class="mb-0">订单汇总</h3>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <div class="d-flex justify-content-between mb-2">
                            <span>商品总价</span>
                            <span id="subtotal">¥{{ subtotal|default:"0.00" }}</span>
                        </div>
                        <div class="d-flex justify-content-between mb-3">
                            <span>折扣金额</span>
                            <span id="discount">-¥0.00</span>
                        </div>
                        <hr>
                        <div class="d-flex justify-content-between h4">
                            <span>应付金额</span>
                            <span id="total">¥{{ subtotal|default:"0.00" }}</span>
                        </div>
                    </div>
                    
                    <button id="checkout-btn" class="btn btn-primary btn-lg btn-block mt-3 {% if not cart_items %}disabled{% endif %}">
                        结算
                    </button>
                    
                    <div class="mt-3">
                        <a href="{% url 'product_list' %}" class="btn btn-outline-secondary btn-block">继续购物</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- AJAX 处理脚本 -->
<script>
$(document).ready(function() {
    // CSRF token 设置
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    const csrftoken = getCookie('csrftoken');

    // 更新购物车数量
    function updateCartQuantity(productId, newQuantity) {
        $.ajax({
            url: "{% url 'update_cart' %}",
            type: "POST",
            data: {
                'product_id': productId,
                'quantity': newQuantity,
                'csrfmiddlewaretoken': csrftoken
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    updateCartTotals(response);
                    // 如果数量为0，移除该商品行
                    if (newQuantity <= 0) {
                        $(`.cart-item[data-product-id="${productId}"]`).remove();
                        if ($('.cart-item').length === 0) {
                            $('#cart-items-container').html(`
                                <div class="text-center py-5">
                                    <i class="fas fa-shopping-cart fa-3x text-muted mb-3"></i>
                                    <p class="text-muted">您的购物车是空的</p>
                                    <a href="{% url 'product_list' %}" class="btn btn-primary">继续购物</a>
                                </div>
                            `);
                            $('#checkout-btn').addClass('disabled');
                        }
                    }
                } else {
                    alert(response.message || '操作失败');
                }
            },
            error: function(xhr, errmsg, err) {
                alert('发生错误: ' + errmsg);
            }
        });
    }

    // 更新总计显示
    function updateCartTotals(data) {
        $('#subtotal').text('¥' + data.subtotal);
        $('#total').text('¥' + data.total);
    }

    // 增加数量
    $(document).on('click', '.quantity-increase', function() {
        const itemDiv = $(this).closest('.cart-item');
        const productId = itemDiv.data('product-id');
        const quantityInput = itemDiv.find('.quantity');
        let quantity = parseInt(quantityInput.val()) + 1;
        quantityInput.val(quantity);
        updateCartQuantity(productId, quantity);
    });

    // 减少数量
    $(document).on('click', '.quantity-decrease', function() {
        const itemDiv = $(this).closest('.cart-item');
        const productId = itemDiv.data('product-id');
        const quantityInput = itemDiv.find('.quantity');
        let quantity = parseInt(quantityInput.val()) - 1;
        
        if (quantity <= 0) {
            if (confirm('确定要移除此商品吗？')) {
                updateCartQuantity(productId, 0);
            } else {
                quantity = 1;
                quantityInput.val(quantity);
            }
        } else {
            quantityInput.val(quantity);
            updateCartQuantity(productId, quantity);
        }
    });

    // 移除商品
    $(document).on('click', '.remove-item', function() {
        if (confirm('确定要移除此商品吗？')) {
            const itemDiv = $(this).closest('.cart-item');
            const productId = itemDiv.data('product-id');
            updateCartQuantity(productId, 0);
        }
    });
});
</script>

<style>
.quantity-btn {
    cursor: pointer;
    user-select: none;
}
.quantity {
    max-width: 40px;
}
.item-subtotal {
    font-weight: bold;
}
.img-placeholder {
    background-color: #f8f9fa;
    border-radius: 4px;
}
</style>
{% endblock %}
